package cn.itcast.server;

import cn.itcast.protocol.MessageCodec;
import cn.itcast.protocol.ProtocolFrameDecoder;
import cn.itcast.server.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class ChatServer{
    public static void main(String[] args) throws Exception {
        // 创建一组线程池
        // 事件循环组 netty 推荐使用两个线程组完成通讯
        // 主线程池：用于接收客户端的请求链接  不做任何处理 将连接转给 worker
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // 从线程池：主线程池会把任务交给它，让它做任务
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        // 线程共享解码器，减少实例次数
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodec MASSAGE_CODEC = new MessageCodec();
        LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        ChatRequestMessageHandler CHAT_HANDLER = new ChatRequestMessageHandler();
        GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();
        GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();
        GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER = new GroupJoinRequestMessageHandler();
        GroupMembersRequestMessageHandler GROUP_MEMBERS_HANDLER = new GroupMembersRequestMessageHandler();
        GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER = new GroupQuitRequestMessageHandler();
        QuitHandler QUIT_HANDLER = new QuitHandler();
        try {
            // 用于服务端启动类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 设置主从线程组
            serverBootstrap.group(bossGroup, workerGroup);
            // 全连接队列大小
            // window服务器不加载服务器配置信息
            // Linux服务器需要修改配置文件  全连接队列 /proc/sys/net/core/somaxconn
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            // 设置nio双向通道
            serverBootstrap.channel(NioServerSocketChannel.class);
            //添加子处理器，用于处理线程池的任务
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    // 需要每个线程单独实例化
                    pipeline.addLast(LOGGING_HANDLER);
                    pipeline.addLast(MASSAGE_CODEC);
                    // 读写空闲检测 处理器
                    pipeline.addLast(new IdleStateHandler(60,0, 0));
                    // Duplex 同时可以对出入栈数据进行处理
                    pipeline.addLast(new ChannelDuplexHandler() {
                        // 用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                        if (evt instanceof IdleStateEvent) {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            switch (event.state()) {
                                case READER_IDLE:
                                    log.debug("读空闲");
                                    // 如果没有心跳的协议，不能直接断开连接，可能会影响正常连接的链接
                                    ctx.channel().close();
                                    break;
                                case WRITER_IDLE:
                                    // 客户端可以使用写事件，触发心跳
                                    log.debug("写空闲");
                                    break;
                                case ALL_IDLE:
                                    log.debug("读写空闲");
                                    break;
                            }
                        }
                        }
                    });
                    pipeline.addLast(new ProtocolFrameDecoder());
                    pipeline.addLast(LOGIN_HANDLER);
                    pipeline.addLast(CHAT_HANDLER);
                    pipeline.addLast(GROUP_CHAT_HANDLER);
                    pipeline.addLast(GROUP_CREATE_HANDLER);
                    pipeline.addLast(GROUP_JOIN_HANDLER);
                    pipeline.addLast(GROUP_MEMBERS_HANDLER);
                    pipeline.addLast(GROUP_QUIT_HANDLER);
                    pipeline.addLast(QUIT_HANDLER);
                }
            });
            // 启动服务，并设置端口，启动方式同步
            ChannelFuture channelFuture = serverBootstrap.bind(8000).sync();
            // 监听关闭的channel,设置为同步方式
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            // 关闭线程组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}




























